package com.csf.context;

import com.csf.annotation.Autowired;
import com.csf.annotation.Component;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.Enumeration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * TODO ADD DESCRIPTION
 * Date: 2018/8/28
 * Time: 18:10
 *
 * @author chenshf
 */
public class IocContext {

    public static final Map<Class<?>, Object> applicationContext = new ConcurrentHashMap<>();

    static {
        scanPackage("com.csf");
        inject();
    }

    public static void inject() {
        try {
            for (Map.Entry<Class<?>, Object> entry : applicationContext.entrySet()) {
                Class<?> clazz = entry.getKey();
                Object obj = entry.getValue();
                Field[] fields = clazz.getDeclaredFields();
                for (Field field : fields) {
                    if (field.isAnnotationPresent(Autowired.class)) {
                        Class<?> fieldClazz = field.getType();
                        field.setAccessible(true);
                        Object fieldObj = applicationContext.get(fieldClazz);
                        field.set(obj, fieldObj);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static void scanPackage(String packageName) {
        try {
            Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(packageName.replaceAll("\\.", "/"));
            while (resources.hasMoreElements()){
                addClassByAnnotation(resources.nextElement().getPath(),packageName);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static void addClassByAnnotation(String path, String packageName) {
        File[] files = getClassFile(path);
        if (files != null) {
            for (File file:files){
                String fileName = file.getName();
                if (file.isFile()) {
                    Class<?> clazz = null;
                    try {
                        clazz = Class.forName(packageName + "." + fileName.substring(0, fileName.lastIndexOf(".")));
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    //判断该类是否实现了注解
                    if(clazz.isAnnotationPresent(Component.class)) {
                        try {
                            applicationContext.put(clazz, clazz.newInstance());
                        } catch (InstantiationException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    addClassByAnnotation(file.getPath(), packageName + "." + fileName);
                }
            }
        }
    }

    private static File[] getClassFile(String path) {
        return new File(path).listFiles(pathname -> pathname.isFile() && pathname.getName().endsWith(".class") || pathname.isDirectory());
    }
}
